package maps;

import maps.utils.Coordinate;
import org.openstreetmap.gui.jmapviewer.JMapViewer;
import org.openstreetmap.gui.jmapviewer.MapMarkerDot;

import java.util.List;

/**
 * Class used for creating dynamic representations of a map from a given list of 
 * coordinates.
 */
public class MapFactory {

	/**
	 * Creates a JMapViewer-object from the provided list of coordinates. The map will be centered at coordinates calculated from the average of all 
	 * the coordinates x- and y-values.
	 * @param coordinates A list of <code>Coordinate</code> objects.
	 * @return A JMapViewer object created with the previously stated specifications.
	 */
    public static JMapViewer createMap(List<Coordinate> coordinates){
        JMapViewer map = new JMapViewer();

        for (Coordinate c : coordinates){
            map.addMapMarker(new MapMarkerDot(c.getX(),c.getY()));
            //We need support for this - i think. wat? /phistu
            //map.addMapMarker(new MapMarkerDot(germanyEastLayer, "Eberstadt", 49.814284999, 8.642065999);
        }

        Coordinate center = findCenter(coordinates);
        //TODO - Appropriate zoom-level needs to be calculated somehow so that
        //all coordinates fit.
        map.setDisplayPositionByLatLon(center.getX(), center.getY(), 15);
        return map;
    }

    /**
     * Calculates the center of the provided list of coordinates. This is calculated by the average of all coordinate's latitude- and longitude values. 
     * @param coordinates A list of <code>Coordinate</code> objects.
     * @return A <code>Coordinate</code> object containing coordinates calculated according to the above specifications.
     */
    private static Coordinate findCenter(List<Coordinate> coordinates){
        int numOfCoords = coordinates.size();
        double sumOfX = 0;
        double sumOfY = 0;

        for (Coordinate c : coordinates){
            sumOfX += c.getX();
            sumOfY += c.getY();
        }

        double avgX = (sumOfX / (double) numOfCoords);
        double avgY = (sumOfY / (double) numOfCoords);

        return new Coordinate(avgX, avgY);
    }
}
